#!/bin/bash

# A script to perform incremental backups using rsync

set -o errexit
set -o nounset
set -o pipefail

readonly SOURCE_DIR="lihao@192.168.101.118:/home/lihao/nginx_work/doc_1/20240226/doc_1/"
readonly BACKUP_DIR="/home/lihao/sda/backup"
readonly DATETIME="$(date '+%Y-%m-%d_%H:%M:%S')"
readonly BACKUP_PATH="${BACKUP_DIR}/${DATETIME}"
readonly LATEST_LINK="${BACKUP_DIR}/latest"

# 记录脚本开始执行的时间
start_time=$(date +%s)

mkdir -p "${BACKUP_DIR}"

# 参数说明
#   采用-a（归档模式）、
#   -v（详细信息）、
#   -z（压缩）、
#   -P（显示进度）和
#   --delete（同步删除）选项
rsync -avzP --delete --rsh=ssh \
  "${SOURCE_DIR}/" \
  --link-dest "${LATEST_LINK}" \
  --exclude=".cache" \
  "${BACKUP_PATH}"

rm -rf "${LATEST_LINK}"
ln -s "${BACKUP_PATH}" "${LATEST_LINK}"
# ln -s /home/lihao/sda/backup/20240918/doc /home/lihao/sda/backup/latest

# 记录脚本结束执行的时间
end_time=$(date +%s)

execution_time=$((end_time - start_time))
echo "Script executed in $execution_time seconds."

# 转换为分钟和秒数
hour=$((execution_time / 3600))
minutes=$(((execution_time % 3600) / 60))
seconds=$((execution_time % 60))

# 输出结果
echo "同步已完成，共运行了 ${hour} 小时 ${minutes} 分钟 ${seconds} 秒。"
